package com.example.writting.ui.words

import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableString
import android.text.SpannableStringBuilder
import android.text.style.RelativeSizeSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.writting.R
import com.example.writting.model.QAStructure
import com.example.writting.model.Content
import com.example.writting.model.ContentType
import com.example.writting.ui.words.adapter.MindMapAdapter

class WordContentAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private var contents: List<Content> = emptyList()

    fun updateContents(newContents: List<Content>) {
        contents = newContents
        notifyDataSetChanged()
    }

    override fun getItemViewType(position: Int): Int {
        return when (contents[position].type) {
            ContentType.QA -> VIEW_TYPE_QA
            ContentType.MNEMONIC -> VIEW_TYPE_MNEMONIC
            ContentType.TABLE -> VIEW_TYPE_TABLE
            ContentType.FLOW -> VIEW_TYPE_FLOW
            ContentType.MINDMAP -> VIEW_TYPE_MINDMAP
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            VIEW_TYPE_QA -> {
                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_qa, parent, false)
                QAViewHolder(view)
            }
            VIEW_TYPE_MNEMONIC -> {
                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_mnemonic, parent, false)
                MnemonicViewHolder(view)
            }
            VIEW_TYPE_TABLE -> {
                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_table, parent, false)
                TableViewHolder(view)
            }
            VIEW_TYPE_FLOW -> {
                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_flow, parent, false)
                FlowViewHolder(view)
            }
            VIEW_TYPE_MINDMAP -> {
                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_mindmap, parent, false)
                MindMapViewHolder(view)
            }
            else -> throw IllegalArgumentException("Invalid view type")
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val content = contents[position]
        when (holder) {
            is QAViewHolder -> holder.bind(content)
            is MnemonicViewHolder -> holder.bind(content)
            is TableViewHolder -> holder.bind(content)
            is FlowViewHolder -> holder.bind(content)
            is MindMapViewHolder -> holder.bind(content)
            is TextViewHolder -> holder.bind(content)
        }
    }

    override fun getItemCount() = contents.size

    inner class QAViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val questionText: TextView = itemView.findViewById(R.id.questionText)
        private val answerAdapter: AnswerAdapter = itemView.findViewById<RecyclerView>(R.id.answerList).let { recyclerView ->
            AnswerAdapter().apply {
                recyclerView.layoutManager = LinearLayoutManager(itemView.context)
                recyclerView.adapter = this
            }
        }
        private val rightArrow: ImageView = itemView.findViewById(R.id.rightArrow)

        fun bind(content: Content) {
            questionText.text = content.title ?: ""
            answerAdapter.updateAnswers(
                content.writtenAnswer?.let { formatQAStructure(it) },
                content.interviewAnswer
            )
            rightArrow.setImageResource(android.R.drawable.ic_media_next)
            rightArrow.setOnClickListener {
                val isShowingWritten = answerAdapter.isShowingWrittenAnswer()
                answerAdapter.toggleAnswer()
                rightArrow.setImageResource(
                    if (isShowingWritten) android.R.drawable.ic_media_previous
                    else android.R.drawable.ic_media_next
                )
            }
        }

        private fun formatQAStructure(qa: QAStructure): CharSequence {
            val builder = SpannableStringBuilder()
            
            qa.majorTitles.forEachIndexed { index, majorTitle ->
                val majorTitleText = "${index + 1}.${majorTitle.title}\n"
                val majorTitleStart = builder.length
                builder.append(majorTitleText)
                builder.setSpan(
                    StyleSpan(Typeface.BOLD),
                    majorTitleStart,
                    builder.length,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                )
                builder.setSpan(
                    RelativeSizeSpan(1.2f),
                    majorTitleStart,
                    builder.length,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                )
                
                majorTitle.content?.takeIf { it.isNotBlank() }?.let {
                    builder.append(it)
                    builder.append("\n")
                }
                
                majorTitle.minorTitles.forEachIndexed { minorIndex, minorTitle ->
                    val minorTitleText = "（${minorIndex + 1}）${minorTitle.title}\n"
                    val minorTitleStart = builder.length
                    builder.append(minorTitleText)
                    builder.setSpan(
                        RelativeSizeSpan(1.1f),
                        minorTitleStart,
                        builder.length,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    
                    if (minorTitle.content.isNotBlank()) {
                        builder.append(minorTitle.content)
                        builder.append("\n")
                    }
                }
            }
            
            return builder
        }
    }

    inner class MnemonicViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val mnemonicTitle: TextView = itemView.findViewById(R.id.mnemonicTitle)
        private val mnemonicContent: TextView = itemView.findViewById(R.id.mnemonicContent)

        fun bind(content: Content) {
            mnemonicTitle.text = content.title ?: ""
            mnemonicContent.text = formatMnemonicText(
                content.content ?: "",
                content.mnemonicKeywords ?: emptyList()
            )
        }

        private fun formatMnemonicText(text: String, keywords: List<String>): SpannableString {
            val spannable = SpannableString(text)
            
            text.replace("\"", "")
            
            keywords.forEach { keyword ->
                val parts = keyword.split("#")
                val keywordText = parts[0]
                val occurrence = parts.getOrNull(1)?.toIntOrNull() ?: 1
                
                var currentIndex = 0
                var count = 0
                
                while (true) {
                    val startIndex = text.indexOf(keywordText, currentIndex)
                    if (startIndex == -1) break
                    
                    count++
                    if (count == occurrence) {
                        spannable.setSpan(
                            StyleSpan(Typeface.BOLD),
                            startIndex,
                            startIndex + keywordText.length,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                        )
                        break
                    }
                    currentIndex = startIndex + 1
                }
            }
            
            return spannable
        }
    }

    inner class TableViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val tableTitle: TextView = itemView.findViewById(R.id.tableTitle)
        private val contentTable: RecyclerView = itemView.findViewById(R.id.contentTable)
        private val tableAdapter = TableAdapter()

        init {
            contentTable.layoutManager = LinearLayoutManager(itemView.context)
            contentTable.adapter = tableAdapter
        }

        fun bind(content: Content) {
            tableTitle.text = content.title ?: ""
            tableAdapter.updateData(
                content.tableData ?: emptyList(),
                itemView.context.resources.displayMetrics.density
            )
        }
    }

    inner class FlowViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val flowTitle: TextView = itemView.findViewById(R.id.flowTitle)
        private val flowContent: RecyclerView = itemView.findViewById(R.id.flowContent)
        private val flowAdapter = FlowAdapter()

        init {
            flowContent.layoutManager = LinearLayoutManager(itemView.context)
            flowContent.adapter = flowAdapter
        }

        fun bind(content: Content) {
            flowTitle.text = content.title ?: ""
            flowAdapter.updateSteps(content.flowSteps ?: emptyList())
        }
    }

    inner class MindMapViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val title: TextView = itemView.findViewById(R.id.title)
        private val mindmapRecyclerView: RecyclerView = itemView.findViewById(R.id.mindmapRecyclerView)
        private val mindMapAdapter = MindMapAdapter()

        init {
            mindmapRecyclerView.layoutManager = LinearLayoutManager(itemView.context)
            mindmapRecyclerView.adapter = mindMapAdapter
        }

        fun bind(content: Content) {
            title.text = content.title
            content.mindMapData?.let { mindMapAdapter.updateMindMap(it) }
        }
    }

    inner class TextViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val title: TextView = itemView.findViewById(R.id.mnemonicTitle)
        private val content: TextView = itemView.findViewById(R.id.mnemonicContent)

        fun bind(content: Content) {
            title.text = content.title ?: ""
            this.content.text = content.content ?: ""
        }
    }

    companion object {
        private const val VIEW_TYPE_QA = 0
        private const val VIEW_TYPE_MNEMONIC = 1
        private const val VIEW_TYPE_TABLE = 2
        private const val VIEW_TYPE_FLOW = 3
        private const val VIEW_TYPE_MINDMAP = 4
    }
}

class AnswerAdapter : RecyclerView.Adapter<AnswerAdapter.AnswerViewHolder>() {
    private var writtenAnswer: CharSequence? = null
    private var interviewAnswer: String? = null
    private var isShowingWritten = true

    fun updateAnswers(written: CharSequence?, interview: String?) {
        writtenAnswer = written
        interviewAnswer = interview
        notifyDataSetChanged()
    }

    fun toggleAnswer() {
        isShowingWritten = !isShowingWritten
        notifyDataSetChanged()
    }

    fun isShowingWrittenAnswer() = isShowingWritten

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AnswerViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_answer, parent, false)
        return AnswerViewHolder(view)
    }

    override fun onBindViewHolder(holder: AnswerViewHolder, position: Int) {
        holder.bind(if (isShowingWritten) writtenAnswer else interviewAnswer, !isShowingWritten)
    }

    override fun getItemCount(): Int = 1

    inner class AnswerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val answerText: TextView = itemView.findViewById(R.id.answerText)

        fun bind(text: CharSequence?, isInterview: Boolean) {
            answerText.text = text ?: "暂无答案"
            answerText.textSize = if (isInterview) 20f else 16f
        }
    }
} 